﻿package net.pezzato.grpbannr{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.display.Stage;
	import net.pezzato.grpbannr.PhotoSliderElement;
	public class PhotoSlider extends Sprite {
		public static  const PHOTO_ADDED:String = "photo added to PhotoSlider";
		private var elements_:Array;
		private var urls_:Array;
		private var maxElementWidth_:Number;
		private var maxElementHeight_:Number;
		private var minPosX_:Number;
		private var nextPosition_:Number;
		public function PhotoSlider(maxElementWidth:Number = 100, maxElementHeight:Number = 100) {
			maxElementWidth_ = maxElementWidth;
			maxElementHeight_ = maxElementHeight;
			elements_ = new Array;
			urls_ = new Array;
			nextPosition_ = 0;
		}
		public function addPhotoFromUrl(url:String) {
			var newElement:PhotoSliderElement = new PhotoSliderElement();
			newElement.addEventListener(PhotoSliderElement.PHOTO_LOADED, onPhotoLoaded);
			newElement.loadFromUrl(url);
		}
		public function addPhotosFromUrlArray(urls:Array) {
			urls_ = urls;
			addNextPhoto();
			addEventListener(PHOTO_ADDED, addNextPhoto);
		}
		private function addNextPhoto(event:Event = null) {
			//trace("Elements: " + elements_.length + " - Urls: " + urls_.length);
			if (elements_.length < urls_.length) {
				addPhotoFromUrl(urls_[elements_.length]);
			} else {
				minPosX_ = stage.stageWidth - nextPosition_;
				addEventListener(Event.ENTER_FRAME, onEnterFrame);
			}
		}
		private function arrangePhoto(num:Number) {
			var element:Sprite = elements_[num];
			element.x = nextPosition_;
			element.y = (maxElementHeight_ - element.height) / 2;
			addChild(element);
			nextPosition_ = element.x + element.width + 5;
			//trace("Element geometry: " + element.width + "x" + element.height + "+" + element.x + "+" + element.y);
		}
		private function onPhotoLoaded(event:Event) {
			elements_.push(event.target);
			arrangePhoto(elements_.length - 1);
			dispatchEvent(new Event(PHOTO_ADDED));
		}
		private function onEnterFrame(event:Event) {
			for (var i:Number = 0; i < elements_.length; ++i) {
				if (elements_[i].x > minPosX_) {
					elements_[i].x -= 1;
				} else {
					elements_[i].x = stage.stageWidth;
				}
			}
		}
	}
}